package com.cwl.common.db;

import cn.hutool.core.lang.ClassScaner;
import com.cwl.common.db.annotation.Table;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Model;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * 功能描述：
 *
 * @author cwledit
 * @date 2019/1/6
 */
@Slf4j
public class TableInfoKit {

    private static List<TableInfo> allTableInfos = Lists.newArrayList();

    public static void initTableInfos(ActiveRecordPlugin activeRecordPlugin, String scanPackage) {
        Set<Class<?>> modelClassList = ClassScaner.scanPackageBySuper("",Model.class);
        log.info("加载model....");
        for (Class<?> clazz : modelClassList) {
            Table tb = clazz.getAnnotation(Table.class);
            if (tb == null) {
                continue;
            }
            if (StringUtils.isNotBlank(scanPackage) && !clazz.getName().startsWith(scanPackage)) {
                continue;
            }
            log.info(scanPackage +"=====>"+ clazz.getName());
            TableInfo tableInfo = new TableInfo();

            tableInfo.setPrimaryKey(tb.primaryKey());
            tableInfo.setTableName(tb.tableName());
            tableInfo.setModelClass((Class<? extends Model>) clazz);
            allTableInfos.add(tableInfo);
            activeRecordPlugin.addMapping(tableInfo.getTableName(), tableInfo.getPrimaryKey(), (Class<? extends Model<?>>) tableInfo.getModelClass());
        }
    }

    public static List<TableInfo> getAllTableInfos() {
        return allTableInfos;
    }

}
